package com.wb.interceptor;

import com.wb.constants.NormalConstant;
import com.wb.entity.UserModel;
import com.wb.service.RedisTokenHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
//@Component(value="loginInterceptor")
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Resource(name = "redisTokenHelp")
    private RedisTokenHelp redisTokenHelp;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //token验证
        String authStr = request.getHeader(NormalConstant.AUTHORIZATION);
        if (redisTokenHelp.existsAuth(authStr)) {
            String userId = redisTokenHelp.get(authStr);
            request.setAttribute("userModel" , new UserModel(userId,authStr, "yanzheng"));
            logger.info(" 通过 userId : {}" , userId);
            return true;
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write("{key:权限未认证}");
        return false;
    }
}
